import { listTrainingPlanByPageUsingPost } from '@/services/backend/trainingPlanController';
import { listUserByPageUsingPost } from '@/services/backend/userController';
import {
  deleteUserTrainingPlanRelationUsingPost,
  listUserTrainingPlanRelationVoByPageUsingPost,
} from '@/services/backend/userTrainingPlanRelationController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, message, Space, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.UserTrainingPlanRelation>();

  const [planEnumMap, setPlanEnumMap] = useState<Map<string, string>>(new Map());

  const [userEnumMap, setUserEnumMap] = useState<Map<string, string>>(new Map());
  const loadPlanList = async () => {
    try {
      const { data, code } = await listTrainingPlanByPageUsingPost({});
      if (code === 0 && data?.records) {
        // 构建 userEnumMap
        const userMap = new Map<string, string>();
        data.records.forEach((plan: API.TrainingPlan) => {
          if (plan.id && plan.planName) {
            userMap.set(plan.id.toString(), plan.planName); // 假设 user 对象有 id 和 name 属性
          }
        });
        setPlanEnumMap(userMap);
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  const loadUserList = async () => {
    try {
      const { data, code } = await listUserByPageUsingPost({
        role: 'user',
      });
      if (code === 0 && data?.records) {
        // 构建 userEnumMap
        const userMap = new Map<string, string>();
        data.records.forEach((user: API.User) => {
          if (user.id && user.username) {
            userMap.set(user.id.toString(), user.username); // 假设 user 对象有 id 和 name 属性
          }
        });
        setUserEnumMap(userMap);
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  useEffect(() => {
    loadUserList();
    loadPlanList();
  }, []);

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.UserTrainingPlanRelation) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteUserTrainingPlanRelationUsingPost({
        id: row.id,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  const columns: ProColumns<API.UserTrainingPlanRelationVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '用户姓名',
      dataIndex: ['user', 'username'],
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '训练名称',
      dataIndex: ['trainingPlan', 'planName'],
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        active: { text: '正在进行', status: 'ongoing' },
        archived: { text: '已完成', status: 'completed' },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size={'middle'}>
          <Typography.Link
            key="config"
            onClick={() => {
              setUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link
            type="danger"
            onClick={() => {
              handleDelete(record);
            }}
          >
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.UserTrainingPlanRelation>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listUserTrainingPlanRelationVoByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.UserTrainingPlanRelationQueryRequest);
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      {/*新增悬浮窗*/}
      <CreateModal
        modalVisible={createModalVisible}
        planEnumMap={planEnumMap}
        userEnumMap={userEnumMap}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      {/*更新悬浮窗*/}
      <UpdateModal
        oldData={currentRow}
        modalVisible={updateModalVisible}
        planEnumMap={planEnumMap}
        userEnumMap={userEnumMap}
        columns={columns}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default TableList;
